import { LayerRange, SampleMethodProps, SampleParameterValues, SampleStepInfo } from "@/pages/auditSampling/typing";
import { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from "react";
import { Button, DataGrid, Popup, RadioGroup, Toolbar } from "devextreme-react";
import { consts } from "@/pages/auditSampling/consts";
import { leftVerticalDivStyle } from "../NonStatSampleService";
import { SampleStepInfoContext } from "../../samplingRecordPopup";
import { Column, Paging } from "devextreme-react/data-grid";
import { msgError } from "@/utils/msg";
import { Item } from "devextreme-react/toolbar";
import { getDevOption, setDevOptions } from "@/utils/pub";
import { nanoid10 } from "@/utils";
import { calcUnSampleSize } from "./LayerSampleService";

/**
 * 区间编辑
 */
export const LayerSampleEditPopup = forwardRef((props: {
    sampleMethodProps: SampleMethodProps
}, ref) => {

    const sampleStepInfo: SampleStepInfo = useContext(SampleStepInfoContext);
    const [visible, setVisible] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);
    const diaParams = useRef<any>();
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (params: any) => {
            diaParams.current = params;

            //恢复做备用
            diaParams.current.oldLayerRanges = JSON.parse(JSON.stringify(
                props.sampleMethodProps.sampleParameterValues.layerSampleParams?.layerRanges || []
            ));

            setVisible(true);
        }
    }))
    function onCancel() {
        //更新数据
        const sampleMethodProps: SampleMethodProps = props.sampleMethodProps;
        //const projectOverallProps = sampleStepInfo.projectOverallProps;\
        //恢复数据
        if (sampleMethodProps.sampleParameterValues?.layerSampleParams) {
            sampleMethodProps.sampleParameterValues.layerSampleParams.layerRanges = diaParams.current?.oldLayerRanges || [];
            props.sampleMethodProps.setSampleParameterValues({ ...sampleMethodProps.sampleParameterValues })
        }
        setVisible(false)
    }
    async function onOKClick() {
        const editDataGridRef = diaParams.current.editDataGridRef;
        await editDataGridRef.current.instance.saveEditData();
        function doOk() {
            setVisible(false)
            if (diaParams.current.onOk) {
                diaParams.current.onOk(true);
            }
        }
        const layerRanges: LayerRange[] = getDevOption(diaParams.current.editDataGridRef, 'dataSource')
        //如果别删除光了,增加默认的
        if (layerRanges.length == 0) {
            return msgError('还没有区间,请增加至少一条!')

        } else {

            if (layerRanges.filter(item => item.rangeValue == undefined).length) {
                return msgError('请设置所有区间的边界值!')
            }
            const keySet: Set<any> = new Set(layerRanges.map(item => item.rangeValue));
            const countKeys: any[] = []
            for (const key of keySet) {
                countKeys.push({
                    value: key,
                    cnt: layerRanges.filter(item => item.rangeValue == key).length
                })
            }
            const repeatValueStr = countKeys.filter(item => item.cnt > 1).map(item => item.value).join('、')

            if (repeatValueStr) {
                return msgError(`这些值 【${repeatValueStr}】 重复设置，请检查！`)
            }

            //排序
            layerRanges.sort((a, b) => (a.rangeValue || 0) - (b.rangeValue || 0))
            layerRanges.forEach((item, index) => item.orderIndex = index + 1)

            const sampleMethodProps: SampleMethodProps = props.sampleMethodProps;
            // const projectOverallProps = sampleStepInfo.projectOverallProps;


            const lastItem_1 = sampleMethodProps.sampleParameterValues.layerSampleParams?.layerRanges?.find(item => item.rangeValue == -1);//rangValue为-1的最后一行
            const newLayerRanges = [...layerRanges.filter(item => item.rangeValue !== -1)];
            //计算未抽样个数
            await calcUnSampleSize(newLayerRanges, sampleStepInfo, sampleMethodProps.sampleParameterValues, lastItem_1)

            //更新数据
            if (sampleMethodProps.sampleParameterValues?.layerSampleParams) {
                sampleMethodProps.sampleParameterValues.layerSampleParams.layerRanges = newLayerRanges;
                props.sampleMethodProps.setSampleParameterValues({ ...sampleMethodProps.sampleParameterValues })
            }

            doOk();
            setLoading(false)
        }

    }
    return <>
        <Popup
            visible={visible}
            title='设置区间'
            width={500}
            height={450}
            onHiding={onCancel}
        >
            {diaParams.current?.dataGrid}
            <Toolbar style={{ marginTop: 20 }}>
                <Item location={'after'}>
                    <Button text='取消' type='normal' disabled={loading} onClick={onCancel} style={{ marginRight: 10 }} />
                    <Button text='确定' type='default' disabled={loading} onClick={onOKClick} />
                </Item>
            </Toolbar>
        </Popup>
    </>
})
/**
 * 分层抽样 参数
 */
export const LayerSample = forwardRef((props: SampleMethodProps, ref: any) => {
    //上级传入的抽样参数
    const sampleStepInfo: SampleStepInfo = useContext(SampleStepInfoContext);


    const layerSampleParams = props.sampleParameterValues?.layerSampleParams || {};
    let layerRanges = props.sampleParameterValues?.layerSampleParams?.layerRanges || [];
    const editLayerRanges = layerRanges.filter(item => item.rangeValue != -1);//编辑时-1为最后一个
    layerRanges.forEach((item, index) => item.orderIndex = index + 1)

    const layerSampleEditPopupRef = useRef<any>();
    const [isNeedLayerSampleEditPopup, setIsNeedLayerSampleEditPopup] = useState<boolean>(false);
    const dataGridRef = useRef<any>();
    const editDataGridRef = useRef<any>();
    //const extractType = props.sampleParameterValues?.layerSampleParams?.extractType || {};
    function getDataGrid(isInEditPopup: boolean, dataGridRef?: any) {
        return <DataGrid
            className='devHeadersCenter PaperDevSortableGrid advancedQueryDataGrid'
            ref={dataGridRef}
            dataSource={isInEditPopup ? editLayerRanges : layerRanges}
            keyExpr="guid"

            showBorders={true}
            showRowLines={true}
            showColumnLines={true}
            rowAlternationEnabled={true}

            height={isInEditPopup ? 300 : undefined}

            allowHeaderFiltering={false}
            allowSorting={false}
            onInitNewRow={(e) => {
                const layerRanges2 = layerRanges.filter(item => item.rangeValue != -1)
                e.data.guid = nanoid10()
                if (layerRanges2 && layerRanges2.length) {
                    e.data.orderIndex = (layerRanges2[layerRanges2.length - 1].orderIndex || 0) + 1;
                } else {
                    e.data.orderIndex = 1
                }
            }}
            //  onSaved={SavedData}
            editing={isInEditPopup ?
                {
                    mode: 'cell', allowDeleting: true, allowUpdating: true, allowAdding: true,
                    texts: { addRow: '增加' }, newRowPosition: 'last'
                }
                : { mode: 'cell', allowDeleting: false, allowUpdating: true, allowAdding: false }}

            onCellPrepared={(e) => {
                if (!isInEditPopup) {
                    if (e.rowType == "data") {//灰色的背景
                        if (e.column.dataField !== 'needSampleSize') {
                            e.cellElement.style.backgroundColor = '#f5f5f5';//灰色
                        } else {
                            e.cellElement.style.backgroundColor = 'white';//白色
                        }
                    }
                }
            }}

            onSaved={(e) => {
                // console.log(e, 'saved ' + new Date().getTime() );
                /*  if (props.sampleParameterValues.layerSampleParams) {
                     props.sampleParameterValues.layerSampleParams.isManualEdit = true;
                     props.setSampleParameterValues({ ...props.sampleParameterValues })
                 } */
            }}

        >
            <Paging enabled={false} />
            {/*   <GridToolbar>
                <GridToolbarItem name="addRowButton" showText="always" />
            </GridToolbar> */}
            <Column
                caption="序号"
                dataField="orderIndex"
                allowEditing={false}
                allowSorting={false}
                alignment='center'
                width={60}
            />
            <Column
                caption="区间值"
                visible={isInEditPopup}
                dataField="rangeValue"
                allowEditing={isInEditPopup}
                allowSorting={false}
                format={consts.numberFormat}
                alignment='center'
                width={150}
            />
            <Column
                caption="区间"
                dataField="rangeText"
                allowEditing={isInEditPopup}
                allowSorting={false}
                alignment='left'
                visible={!isInEditPopup}
            //width={200}
            />

            <Column
                caption="待抽样数量"
                dataField="unSampleSize"
                allowEditing={false}
                allowSorting={false}
                alignment='center'
                visible={!isInEditPopup}
                width={100}
            />

            <Column
                caption="抽取数量"
                dataField="needSampleSize"
                allowEditing={true}
                allowSorting={false}
                alignment='center'
                visible={!isInEditPopup}
                dataType={'number'}
                editorOptions={{ min: 0 }}
                width={100}
            />
            <Column
                caption="已抽数量"
                dataField="sampledResult.sampledSize"
                allowEditing={false}
                allowSorting={false}
                alignment='center'
                visible={!isInEditPopup}
                width={100}

            />
            <Column
                caption="操作"
                type={'buttons'}
                width={80}
                visible={isInEditPopup}
            />
        </DataGrid>
    }
    //打开编辑
    function openEditPopup() {
        setIsNeedLayerSampleEditPopup(true)
        const interval = setInterval(() => {
            if (layerSampleEditPopupRef.current) {
                clearInterval(interval)
                setDevOptions(editDataGridRef, { 'dataSource': editLayerRanges })
                layerSampleEditPopupRef.current.show({
                    dataGrid: getDataGrid(true, editDataGridRef),
                    editDataGridRef,
                    //sampleMethodProps: props,
                    onOk: () => {
                        //setDevOptions
                        layerRanges = props.sampleParameterValues?.layerSampleParams?.layerRanges || []

                        setDevOptions(dataGridRef, { 'dataSource': layerRanges })
                        dataGridRef.current?.instance?.refresh();
                        setIsNeedLayerSampleEditPopup(false)
                    }
                })
            }
        }, 10);

    }
    /**
     *  重新计算未抽样数量
     */
    async function reCalcUnSampleSize(sampleParameterValues: SampleParameterValues, isNeedSet: boolean) {

        console.time('reCalcUnSampleSize')
        // const sampleMethodProps: SampleMethodProps = props;
        // const projectOverallProps = sampleStepInfo.projectOverallProps;
        const layerRanges = sampleParameterValues.layerSampleParams?.layerRanges || []
        const lastItem_1 = layerRanges.find(item => item.rangeValue == -1);//rangValue为-1的最后一行
        const newLayerRanges = [...layerRanges.filter(item => item != lastItem_1)];
        //计算未抽样个数
        await calcUnSampleSize(newLayerRanges, sampleStepInfo, sampleParameterValues, lastItem_1)

        //更新数据
        if (isNeedSet && sampleParameterValues?.layerSampleParams) {
            sampleParameterValues.layerSampleParams.layerRanges = newLayerRanges;
            props.setSampleParameterValues({ ...sampleParameterValues })
        }
        console.timeEnd('reCalcUnSampleSize')
    }
    //保存编辑数据(抽样界面)
    function saveEditData() {
        dataGridRef.current.instance.saveEditData();
    }
    useEffect(() => {
        if (ref) {
            ref.current = { reCalcUnSampleSize, saveEditData }
        }
    }, [])
    /**
     * 是否需要重算
     */
    function getNeedReCalcCount() {
        /*  let allUnSapmleSize = 0;
         layerRanges.forEach(item => {
             allUnSapmleSize += item.unSampleSize || 0;
         })
         return allUnSapmleSize !== props.sampleParameterValues.toBeTestSampleSize ? 1 : 0 */
        return 0;
    }
    return <>
        {isNeedLayerSampleEditPopup &&
            <LayerSampleEditPopup ref={layerSampleEditPopupRef}
                // layerRanges={editLayerRanges} //编辑时-1是最后一个,不显示
                sampleMethodProps={props} />
        }
        <div className="itemBoxDispalyLeft">
            <div className="itemBoxDispalyLeft"
                style={{ marginLeft: 0, height: 125, border: '1px solid #e5e5e5', borderRadius: 5, width: '660px' }}  >
                {/*  <div style={leftVerticalDivStyle}>
                    <div>区</div>
                    <div>间</div>
                </div> */}
                <div className="for-button-padding5" >
                    <Button text={`设置(${layerRanges.length})`} icon='preferences' type="default" style={{ marginTop: 5 }}
                        height={35}
                        width={110}
                        onClick={openEditPopup}
                    />

                    <Button text={`计算待抽样数量`} style={{ marginTop: 5, marginLeft: 3, padding: 0, marginRight: 5 }} height={35}
                        onClick={() => reCalcUnSampleSize(props.sampleParameterValues, true)}
                    />
                    {/* <div style={{ margin: 2,  }}>待抽样的测试总体: {props.sampleParameterValues.toBeTestSampleSize}</div> */}
                </div>
                {getDataGrid(false, dataGridRef)}
            </div>

            <div className="itemBoxDispalyLeft"
                style={{ marginLeft: 10, height: 125, border: '1px solid #e5e5e5', borderRadius: 5, width: 'calc(100% - 660px)' }}  >
                <div style={leftVerticalDivStyle}>
                    <div>抽</div>
                    <div>取</div>
                </div>
                <div className="" style={{ width: '100%', paddingLeft: 10, paddingTop: 10 }}>
                    <RadioGroup
                        dataSource={consts.amountExtractMethodArray}
                        value={layerSampleParams.extractType}
                        //layout="horizontal"
                        valueExpr={'value'}
                        displayExpr={'text'}
                        onValueChanged={(e) => {
                            layerSampleParams.extractType = e.value;
                            props.setSampleParameterValues({ ...props.sampleParameterValues })
                        }}
                    />

                </div>
            </div>

        </div >
    </>
})